//
//  LXContentView.swift
//  LXPageView
//
//  Created by seven on 2017/11/9.
//  Copyright © 2017年 seven. All rights reserved.
//

import UIKit

protocol LXContentViewDelegete: class {
    func contentView(_ contentView: LXContentView, targetIndex: Int)
    func contentView(_ contentView: LXContentView, sourceIndex: Int,targetIndex: Int, progress: CGFloat)
}

private let cellIdentifer = "contentCellIdentifer"
class LXContentView: UIView {
    
    weak var delegete: LXContentViewDelegete?
    private var childVcs: [UIViewController]
    private var parentVc: UIViewController
    private var startOffetX: CGFloat = 0
    private var isForbidScroll: Bool = false
    
    private lazy var collecetionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = self.bounds.size
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
        let collecetionView = UICollectionView(frame: self.bounds, collectionViewLayout: layout)
        collecetionView.dataSource = self
        collecetionView.delegate = self
        collecetionView.isPagingEnabled = true
        collecetionView.bounces = false
        collecetionView.scrollsToTop = false
        collecetionView.showsHorizontalScrollIndicator = false
        collecetionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellIdentifer)
        return collecetionView
    }()
    
    init(frame: CGRect, childVcs: [UIViewController], parentVc: UIViewController) {
        self.childVcs = childVcs
        self.parentVc = parentVc
        
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension LXContentView{
    private func setupUI(){
        //将所有子控制器添加到父控制器中
        childVcs.forEach { (childVc) in
            parentVc.addChildViewController(childVc)
        }
        //添加collectionView用于显示内容
        addSubview(collecetionView)
    }
}

//MARK:- collectionView代理和数据源
extension LXContentView: UICollectionViewDataSource,UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return childVcs.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifer, for: indexPath)
        cell.contentView.subviews.forEach { (subview) in
            subview.removeFromSuperview()
        }
        let childVc = childVcs[indexPath.item]
        childVc.view.frame = cell.contentView.bounds
        cell.contentView.addSubview(childVc.view)
        
        return cell
    }
    
    //delegete
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        startOffetX = scrollView.contentOffset.x
        isForbidScroll = false
    }
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        contentEndScroll()
        scrollView.isScrollEnabled = true
    }
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if !decelerate{
            contentEndScroll()
        }else{
            scrollView.isScrollEnabled = false
        }
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //判断是否是进制状态
        //0.和开始时偏移量是否一致
        guard startOffetX != scrollView.contentOffset.x,!isForbidScroll else{return}
        //1.定义targetIndex/progress
        var targetIndex = 0
        var progress: CGFloat = 0.0
        //2.给targetIndex和progress赋值
        let currentIndex = Int(startOffetX / scrollView.bounds.width)
        
        if startOffetX < scrollView.contentOffset.x{//用户在左滑
            targetIndex = currentIndex + 1
            if targetIndex > childVcs.count - 1 {
                targetIndex = childVcs.count - 1
            }
            progress = (scrollView.contentOffset.x - startOffetX) / scrollView.bounds.width
        }else{//右滑
            targetIndex = currentIndex - 1
            if targetIndex < 0 {
                targetIndex = 0
            }
            progress = (startOffetX - scrollView.contentOffset.x) / scrollView.bounds.width
        }
        
        //3.通知代理
        delegete?.contentView(self, sourceIndex: currentIndex, targetIndex: targetIndex, progress: progress)
        
    }
    
    private func contentEndScroll(){
        //判断是否是禁止状态
        guard !isForbidScroll else {return}
        //1.获取滚动到的位置
        let currentIndex =  Int(collecetionView.contentOffset.x / collecetionView.bounds.width)
        //通知titleView 进行调整位置
        delegete?.contentView(self, targetIndex: currentIndex)
    }
}

//MARK:- 遵守titleView的代理
extension LXContentView: LXTitleViewDelegete{
    func titleView(_ titleView: LXTitleView, targetIndex: Int) {
        isForbidScroll = true
        let indexPath = IndexPath(item: targetIndex, section: 0)
        collecetionView.scrollToItem(at: indexPath, at: .left, animated: false)
    }
}
